package juanma;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JTextField;
import javax.swing.JLabel;

import java.awt.Font;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


public class Main extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private JTextField textAgregar;
	private JTree treeBackpacks;
	private Backpack backpackSeleccionado;
	private ArrayList<Backpack> listaBackpacks;
	private JTextField txtNombre;
	private JTextField txtPrecio;
	private JTextField txtPeso;
	private JTextField txtCantidad;
	private JLabel lblMgia;
	private JTextPane txtpnMagia;
	private JTextPane txtpnNotas;
	private JCheckBox chkboxMagico;
	private JCheckBox chkboxEquipado;
	private JTable tableItems;
	private JButton btnEditarItem;

	public Main() {
		setTitle("Backpacks");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 654, 355);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		listaBackpacks = new ArrayList<Backpack>();
		
		final JLabel lblBackpack = new JLabel("");
		lblBackpack.setForeground(Color.DARK_GRAY);
		lblBackpack.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblBackpack.setBounds(144, 14, 151, 14);
		contentPane.add(lblBackpack);
		
	//TreeBackpacks
		treeBackpacks = new JTree();
		treeBackpacks.setModel(new DefaultTreeModel(
			new DefaultMutableTreeNode("Backpacks") {
				private static final long serialVersionUID = 1L;
			}
		));
		treeBackpacks.setBounds(10, 11, 124, 226);
		contentPane.add(treeBackpacks);
		treeBackpacks.addTreeSelectionListener(new TreeSelectionListener(){
			@Override
			//Muestra los items del backpack seleccionado
			public void valueChanged(TreeSelectionEvent arg0) {
				backpackSeleccionado = buscarBackpackSeleccionado();
				if(backpackSeleccionado != null){
					lblBackpack.setText(backpackSeleccionado.nombre.toUpperCase() + ":");
					DefaultTableModel tableModel = (DefaultTableModel)tableItems.getModel();
					removerFilas(tableModel);			
					for(Item itemActual : backpackSeleccionado){
						String[] datosActuales = {String.valueOf(itemActual.getCantidad()), itemActual.nombre};
						tableModel.addRow(datosActuales);
					}
					tableModel.fireTableDataChanged();
				}
			}			
		});
		
		textAgregar = new JTextField();
		textAgregar.setBounds(10, 283, 124, 20);
		contentPane.add(textAgregar);
		textAgregar.setColumns(10);
		
		JLabel lblAgregarBackpack = new JLabel("AGREGAR BACKPACK");
		lblAgregarBackpack.setForeground(Color.GRAY);
		lblAgregarBackpack.setFont(new Font("Courier New", Font.PLAIN, 12));
		lblAgregarBackpack.setBounds(10, 268, 124, 14);
		contentPane.add(lblAgregarBackpack);
		
		
	//Agregar item
		JButton btnAgregarItem = new JButton("Agregar Item");
		btnAgregarItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Backpack backpack = buscarBackpackSeleccionado();
				if(backpack != null){
					WinAgregarItem.main(backpack, tableItems);
				}
			}
		});
		btnAgregarItem.setBounds(144, 282, 151, 23);
		contentPane.add(btnAgregarItem);
		
		txtNombre = new JTextField();
		txtNombre.setEditable(false);
		txtNombre.setBounds(346, 28, 155, 23);
		contentPane.add(txtNombre);
		txtNombre.setColumns(10);
		
		txtPrecio = new JTextField();
		txtPrecio.setEditable(false);
		txtPrecio.setColumns(10);
		txtPrecio.setBounds(513, 28, 49, 23);
		contentPane.add(txtPrecio);
		
		txtPeso = new JTextField();
		txtPeso.setEditable(false);
		txtPeso.setColumns(10);
		txtPeso.setBounds(572, 28, 49, 23);
		contentPane.add(txtPeso);
		
		txtCantidad = new JTextField();
		txtCantidad.setEditable(false);
		txtCantidad.setColumns(10);
		txtCantidad.setBounds(310, 28, 30, 23);
		contentPane.add(txtCantidad);
		
		chkboxMagico = new JCheckBox("M\u00E1gico");
		chkboxMagico.setEnabled(false);
		chkboxMagico.setBounds(513, 58, 97, 23);
		contentPane.add(chkboxMagico);
		
		chkboxEquipado = new JCheckBox("Equipado");
		chkboxEquipado.setEnabled(false);
		chkboxEquipado.setBounds(513, 84, 97, 23);
		contentPane.add(chkboxEquipado);
		
		txtpnNotas = new JTextPane();
		txtpnNotas.setEditable(false);
		txtpnNotas.setBounds(320, 81, 179, 66);
		contentPane.add(txtpnNotas);
		
		JLabel lblNotas = new JLabel("NOTAS");
		lblNotas.setFont(new Font("Tahoma", Font.PLAIN, 10));
		lblNotas.setBounds(320, 67, 46, 14);
		contentPane.add(lblNotas);
		
		lblMgia = new JLabel("MAGIA");
		lblMgia.setFont(new Font("Tahoma", Font.PLAIN, 10));
		lblMgia.setBounds(320, 161, 46, 14);
		contentPane.add(lblMgia);
		
		txtpnMagia = new JTextPane();
		txtpnMagia.setEditable(false);
		txtpnMagia.setBounds(320, 175, 179, 63);
		contentPane.add(txtpnMagia);
		
		tableItems = new JTable();
		tableItems.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"#", "Item"
			}
		) {
			private static final long serialVersionUID = 1L;
			boolean[] columnEditables = new boolean[] {
				false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		tableItems.getColumnModel().getColumn(0).setResizable(false);
		tableItems.getColumnModel().getColumn(0).setPreferredWidth(30);
		tableItems.getColumnModel().getColumn(0).setMinWidth(30);
		tableItems.getColumnModel().getColumn(0).setMaxWidth(30);
		tableItems.getColumnModel().getColumn(1).setResizable(false);
		tableItems.setBounds(144, 28, 151, 209);
		contentPane.add(tableItems);
		
		btnEditarItem = new JButton("Editar Item");
		btnEditarItem.setBounds(144, 248, 111, 23);
		contentPane.add(btnEditarItem);
		
		JButton btnUsar = new JButton("-");
		btnUsar.setBounds(257, 248, 38, 23);
		contentPane.add(btnUsar);
		btnUsar.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				//Usar item
				Item item = buscarItemSeleccionado();
				if(item != null){
					if(item.getCantidad() > 0){
						item.usarItem();
						String cantidadActual = String.valueOf(item.getCantidad());
						int fila = tableItems.getSelectedRow();
						tableItems.getModel().setValueAt(cantidadActual, fila, 0);
						txtCantidad.setText(cantidadActual);
					} else{
						JOptionPane.showMessageDialog(null, "No te quedan " + item.nombre + "!");
					}
				}
			}
		});
		
		btnEditarItem.addActionListener(new ActionListener(){
			//Edita el item seleccionado
			@Override
			public void actionPerformed(ActionEvent e) {
				Item item = buscarItemSeleccionado();
				if(item != null)
					WinEditarItem.main(item, tableItems);
			}
		});
		
		tableItems.addMouseListener(new MouseListener(){
			//Mostrar item seleccionad
			@Override
			public void mouseClicked(MouseEvent e) {
				Item item = buscarItemSeleccionado();
				if(item != null)
					mostrarAtributos(item);
			}
			@Override
			public void mouseEntered(MouseEvent e) {
			}
			@Override
			public void mouseExited(MouseEvent e) {
			}
			@Override
			public void mousePressed(MouseEvent e) {
			}
			@Override
			public void mouseReleased(MouseEvent e) {
			}
		});
		tableItems.getModel().addTableModelListener(new TableModelListener(){
			@Override
			public void tableChanged(TableModelEvent arg0) {
				Item item = buscarItemSeleccionado();
				if(item != null){
					mostrarAtributos(item);
				}
			}
		});
		
		//Agregar backpack
		textAgregar.addKeyListener(new KeyListener(){
			@Override
			public void keyPressed(KeyEvent arg0) {
			}
			@Override
			public void keyReleased(KeyEvent arg0) {
			}
			@Override
			public void keyTyped(KeyEvent tecla) {
				if(tecla.getKeyChar() == 10 && !textAgregar.getText().matches("")){
					DefaultTreeModel model = (DefaultTreeModel)treeBackpacks.getModel();
					DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot();
					agregarNodo(root, textAgregar.getText());
					listaBackpacks.add(new Backpack(textAgregar.getText()));
					textAgregar.setText("");
					model.reload();
				}
			}
			
		});
	}
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Main frame = new Main();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	private void agregarNodo(DefaultMutableTreeNode nodoPadre, String nombreHijo){
		DefaultMutableTreeNode nodoNuevo = new DefaultMutableTreeNode(nombreHijo);
		nodoPadre.add(nodoNuevo);
	}
	
	@SuppressWarnings("unused")
	private Backpack buscarBackpack(DefaultMutableTreeNode nodoBackpack){
	//POST: retorna el backpack correspondiente al nodoBackpack
	//	Retorna null si el parametro es null o si es el root
		Backpack backpack = null;
		DefaultMutableTreeNode root = (DefaultMutableTreeNode)treeBackpacks.getModel().getRoot();
		if(nodoBackpack != null && nodoBackpack != root){
			int index = 0;
			do{
				backpack = listaBackpacks.get(index++);
			}while(index<listaBackpacks.size() && 
					!backpack.nombre.matches((String)nodoBackpack.getUserObject()));
		}
		return backpack;
	}
	
	private Backpack buscarBackpackSeleccionado(){
	//POST: retorna el backpack correspondiente al nodo seleccionado
	//	Retorna null si no hay nada seleccionado o si es el root
		DefaultMutableTreeNode nodoBackpack =
				(DefaultMutableTreeNode)treeBackpacks.getLastSelectedPathComponent();
		DefaultMutableTreeNode root = (DefaultMutableTreeNode)treeBackpacks.getModel().getRoot();
		Backpack backpack = null;
		if(nodoBackpack != null && nodoBackpack != root){
			int index = 0;
			do{
				backpack = listaBackpacks.get(index++);
			}while(index<listaBackpacks.size() && 
					!backpack.nombre.matches((String)nodoBackpack.getUserObject()));
		}
		return backpack;
	}
	
	private Item buscarItemSeleccionado(){
	//POST: retorna el ultimo item seleccionado
		int filSelec = tableItems.getSelectedRow();
		Item itemSeleccionado = null;
		if(filSelec != -1){
			String nombreItem = (String) tableItems.getValueAt(filSelec, 1);
			itemSeleccionado = backpackSeleccionado.buscarItem(nombreItem);
		}
		return itemSeleccionado;
	}
	
	private void removerFilas(DefaultTableModel tableModel){
		for(int i=tableModel.getRowCount(); i>0; i--){
			tableModel.removeRow(0);
		}
	}
	
	private void mostrarAtributos(Item item){
		txtCantidad.setText(String.valueOf(item.getCantidad()));
		txtNombre.setText(item.nombre);
		txtPrecio.setText("$ " + String.valueOf(item.getPrecio()));
		txtPeso.setText(String.valueOf(item.getPeso()) + " pn");
		chkboxMagico.setSelected(item.magico);
		chkboxEquipado.setSelected(item.equipado);
		txtpnNotas.setText(item.notas);
		txtpnMagia.setText(item.magia);
	}
	
}
